package homelesspartners.client.model;

import homelesspartners.client.ServerFacade;

import java.util.ArrayList;

/**
 * Singleton class for handling the pagination of thank you notes
 * 
 * @author Greg Ashby
 */
public class ThankYouPages {

	public static final int PAGE_SIZE = 20;
	private static ThankYouPages instance = new ThankYouPages();

	private ArrayList pages = new ArrayList();

	private int pageNumber = 0;

	public ArrayList getPage() {
		if (isPastLastPage()) {
			ServerFacade.loadPageOfThankYous(pageNumber * PAGE_SIZE);
			return null;
		}
		return (ArrayList) pages.get(pageNumber);
	}

	private boolean isPastLastPage() {
		return pages.size() <= pageNumber;
	}

	public boolean nextPage() {
		if (isPastLastPage()) {
			return false;
		}
		pageNumber++;
		return true;
	}

	public boolean previousPage() {
		if (pageNumber == 0) {
			return false;
		}
		pageNumber--;
		return false;
	}

	public boolean hasMore() {
		// true if it's not on the last page OR it's on the last page but that page is full
		// ie. meaning you have to check the server to see if there's more
		if(pageNumber < pages.size() - 1){
			return true;
		} else if (isLastPage()){
			return ((ArrayList) pages.get(pageNumber)).size() == PAGE_SIZE ? true: false;
		}
		return false;
	}
	public boolean hasPrevious() {
		if(pageNumber > 0) {
			return true;
		}
		return false;
	}

	public int getCurrentPageStartIndex() {
		return pageNumber * PAGE_SIZE + 1;
	}

	public int getCurrentPageEndIndex() {
		// simple case: pageNumber * PAGE_SIZE + PAGE_SIZE
		// complex case, on the last page, pageNumber * PAGE_SIZE + lastPage.size()
		int base = pageNumber * PAGE_SIZE;
		if(isLastPage()) {
			return base + ((ArrayList)pages.get(pageNumber)).size();
		} 
		return base + PAGE_SIZE;
	}

	private boolean isLastPage() {
		return pageNumber == pages.size() - 1;
	}

	public static ThankYouPages getInstance() {
		return instance;
	}

	public void flush() {
		pages = new ArrayList();
	}

	public void addPage(ArrayList list) {
		pages.add(list);
	}
}
